package main

import "fmt"

func testSlice0() {
  var a []int //此时只是个空切片
  if a == nil /*←空的 什么也没有*/ {
    fmt.Printf("a is nil\n")
  } else {
    fmt.Printf("a=%v\n", a)
  }

  //此时切片还什么都没有
  //不能进行操作
  //a[0]=100 //panic: runtime error: index out of range [0] with length 0


  //可以先跳过 先看 15切片---使用make来创建切片, 再回来看这里
  //空切片也可以被append
  a = append(a, 100)
  fmt.Printf("%p,   len:%d, cap:%d\n",a,len(a),cap(a)) //0xc00000a0c0,   len:1, cap:1
  a = append(a, 200)
  fmt.Printf("%p,   len:%d, cap:%d\n",a,len(a),cap(a)) //0xc00000a0d0,   len:2, cap:2
  a = append(a, 300)
  fmt.Printf("%p,   len:%d, cap:%d\n",a,len(a),cap(a)) //0xc000010340,   len:3, cap:4
  a = append(a, 400)
  fmt.Printf("%p,   len:%d, cap:%d\n",a,len(a),cap(a)) //0xc000010340,   len:4, cap:4
  a = append(a, 500)
  fmt.Printf("%p,   len:%d, cap:%d\n",a,len(a),cap(a)) //0xc00000e3c0,   len:5, cap:8

  //扩容策略为翻倍扩容
}

//切片初始化方式①
//基于一个已有数组创建一个切片
func testSlice1() {
  a := [5]int{76, 77, 78, 79, 80}
  var b []int = a[1:4] //基于数组a创建一个切片, 包括元素a[1] a[2] a[3]
  fmt.Printf("slice b:%v\n", b)
  fmt.Printf("b[0]=%d\n", b[0])
  fmt.Printf("b[1]=%d\n", b[1])
  fmt.Printf("b[2]=%d\n", b[2])
}

//切片初始化方式②
//直接初始化一个切片
func testSlice2() {
  a := []int{76, 77, 78, 79, 80}
  fmt.Printf("slice a:%v\n", a)
  fmt.Printf("type of a:%T\n", a)
}

//基本操作
func testSlice3() {
  a := [5]int{76, 77, 78, 79, 80}
  var b []int
  b = a[1:4]
  fmt.Printf("slice b:%v\n", b) //slice b:[77 78 79]
  c := a[1:]
  fmt.Printf("slice c:%v\n", c) //slice c:[77 78 79 80]
  d := a[:3]
  fmt.Printf("slice d:%v\n", d) //slice d:[76 77 78]
  e := a[:]
  fmt.Printf("slice e:%v\n", e) //slice e:[76 77 78 79 80]
}

//切片是对原数组的引用
func testSlice4() {
  a := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  fmt.Printf("array a:%v type of a:%T\n", a, a)

  b := a[2:5]
  fmt.Printf("slice b:%v type of b:%T\n", b, b)

  //b[0] = b[0]+10
  //b[1] = b[1]+20
  //b[2] = b[2]+30
  for index := range b {
    b[index] = b[index] + 10
  }
  fmt.Printf("after modify slice b, array a:%v type of a:%T\n", a, a)
  /*
     array a:[1 2 3 4 5 6 7 8 9 10] type of a:[10]int
     slice b:[3 4 5] type of b:[]int
     after modify slice b, array a:[1 2 13 24 35 6 7 8 9 10] type of a:[10]int
  */
}
func testSlice5() {
  a := [...]int{1, 2, 3}
  s1 := a[:]
  s2 := a[:]
  s1[0] = 100
  fmt.Printf("a=%v s2=%v\n", a, s2)
  s2[1] = 200
  fmt.Printf("a=%v s1=%v\n", a, s1)

  /*
     a=[100 2 3] s2=[100 2 3]
     a=[100 200 3] s1=[100 200 3]
  */
}
func main() {
  testSlice0()

  //testSlice1()
  /*
     slice b:[77 78 79]
     b[0]=77
     b[1]=78
     b[2]=79
  */

  //testSlice2()
  /*
     slice a:[76 77 78 79 80]
     type of a:[]int
  */

  //testSlice3()

  //testSlice4()

  //testSlice5()
}
